import os
import json
from services.PageInfo import *
import utils.mylog as logging
from utils.myconfig import *

class Device:
    def __init__(self, id):
        self.id = id
        self.logger = logging.getLogger(self.__class__.__name__)

    def connect(self):
        self.driver = UiDriver.connect(device_sn=self.id)

    def disconnect(self):
        self.driver.close()
        self.driver = None

    def get_widget_tree_json(self):
        # 获取控件树
        widget_file_name = "widget_tree.json"
        widget_file_path = os.path.join(TMP_HOME, widget_file_name)
        self.driver.hdc(f"hdc shell uitest dumpLayout -p /data/local/tmp/{widget_file_name}")
        self.driver.hdc(f"hdc file recv /data/local/tmp/{widget_file_name} {widget_file_path}")
        self.driver.hdc(f"hdc shell rm -rf recv /data/local/tmp/{widget_file_name}")
        # 读取为json

        with open(f"{widget_file_path}", 'r', encoding='utf - 8') as file:
            data = json.load(file)
            return data
        return 1

    def get_screencap(self, picture_name):
        picture_path = os.path.join(TMP_HOME, picture_name)
        if os.path.exists(picture_path):
            self.logger.info(f"{picture_path} exists")
            return picture_path
        self.driver.hdc(f"hdc shell uitest screenCap -p /data/local/tmp/{picture_name}")
        self.driver.hdc(f"hdc file recv /data/local/tmp/{picture_name} {picture_path}")
        self.driver.hdc(f"hdc shell rm -rf recv /data/local/tmp/{picture_path}")
        return picture_path